package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.entity.AdChannel;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.service.AdChannelService;
import com.usian.common.dtos.PageResult;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.util.BeanHelper;
import com.usian.model.admin.dtos.ChannelDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {
    @Override
    public PageResult<ChannelDto> findPage(ChannelDto dto) {
        //参数校验
        if(dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //封装分页条件
        Page<AdChannel> page = new Page<>(dto.getPage(),dto.getSize());
        //封装查询条件  根据频道名称模糊查询
        QueryWrapper<AdChannel> queryWrapper = new QueryWrapper<>();
        String name = dto.getName();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.lambda().like(AdChannel::getName,dto.getName());
        }
        //执行查询
        IPage<AdChannel> iPage = this.page(page, queryWrapper);
        //将AdChannel结果集，转为ChannelDto
        List<AdChannel> records = iPage.getRecords();
        if(CollectionUtils.isEmpty(records)){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<ChannelDto> dtoList = BeanHelper.copyWithCollection(records, ChannelDto.class);

        PageResult<ChannelDto> pageResult = new PageResult<>(dto.getPage(),dto.getSize(),iPage.getTotal(),dtoList);
        return pageResult;
    }

    @Override
    public void deleteById(Integer id) {
        //查询频道数据，判断频道的状态
        AdChannel adChannel = this.getById(id);
        if(adChannel==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取频道状态
        Boolean status = adChannel.getStatus();
        if (status) {
            //有效状态频道不能删除
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"有效状态频道不能删除");
        }
        //删除频道
        this.removeById(id);
    }
}
